﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bridge.Workflow.Domain;
using Bridge.Workflow.EntityFrameworkCore.Persistence;
using Bridge.Workflow.Users;
using Newtonsoft.Json;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;
using Volo.Abp.Uow;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using Volo.Abp.Users;
using Bridge.Workflow.Extensions;
using Users;

namespace Bridge.Workflow.Application
{
    /// <summary>
    /// 指定角色审批
    /// </summary>
    public class RoleAuditingStepBodyService : StepBody, ITransientDependency
    {
        private const string ActionName = "AuditEvent";
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAbpPersistenceProvider _abpPersistenceProvider;
        private readonly IUserService _userService;
        private readonly IRepository<PersistedWorkflowAuditor, string> _auditorRepository;
        private readonly ICurrentUser _currentUser;

        public RoleAuditingStepBodyService
            (IUnitOfWork unitOfWork,
            IUserService userService,
            IAbpPersistenceProvider abpPersistenceProvider,
            IRepository<PersistedWorkflowAuditor, string> auditorRepository,
            ICurrentUser currentUser)
        {
            _unitOfWork = unitOfWork;
            _abpPersistenceProvider = abpPersistenceProvider;
            _userService = userService;
            _auditorRepository = auditorRepository;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 审核角色
        /// </summary>
        public string RoleName { get; set; }

        /// <summary>
        /// 角色ID
        /// </summary>
        public string RoleId { get; set; }


        /// <summary>
        /// 步骤执行逻辑处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        [UnitOfWork]
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            return ExecutionRunAsync(context).Result;
        }

        public class UserList
        {
            public string Name { get; set; }
            public Guid Id { get; set; }
        }

        /// <summary>
        /// 生成审核记录
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task<ExecutionResult> ExecutionRunAsync(IStepExecutionContext context)
        {
            List<IdentityUserDto> userLists = new();
            var workflow = await _abpPersistenceProvider.GetPersistedWorkflow(context.Workflow.Id);
            var userIdentityName = await _userService.WfGetAsyncById(workflow.CreatorId ?? Guid.Empty);
            
            userLists = await _userService.GetUserListByRoleName(Guid.Parse(RoleName));
      
            if(userLists.Count() == 0)
            {
                context.Workflow.Status = WorkflowStatus.Complete;
                return ExecutionResult.Next();
            }

            if (!context.ExecutionPointer.EventPublished)
            {
                
                WorkflowData BusinessData = JsonConvert.DeserializeObject<WorkflowData>(workflow?.Data);
                var workflowDefinition = await _abpPersistenceProvider.GetPersistedWorkflowDefinition(context.Workflow.WorkflowDefinitionId, context.Workflow.Version);

                //var userIdentityName = await _userManager.GetAsyncById(workflow.CreatorId ?? Guid.Empty);
                //var userIdentityName = await _userManager.WfGetAsyncById(workflow.CreatorId ?? Guid.Empty);

                //if (Guid.TryParse(BusinessData.AgencyId, out Guid agencyId) == false)
                //{

                //    agencyId = new Guid(userIdentityName.AgencyName) ;
                //}
                //userLists = await _userManager.GetUserListByRoleName(Guid.Parse(RoleName), agencyId);

                #region 通知审批人
                //var notifyData = new NotificationData();
                //notifyData.Properties["content"] = $"【{userIdentityName}】提交的{workflowDefinition.Title}需要您审批！";
                //_notificationPublisher.PublishAsync("Task", notifyData,
                //    userIds: userIdentitys.Select(u => new UserIdentifier(u.TenantId, u.Id)).ToArray(),
                //     entityIdentifier: new EntityIdentifier(workflow.GetType(), workflow.Id)
                //    ).Wait();
                #endregion

                var count = await _auditorRepository.CountAsync(s => s.ExecutionPointerId == context.ExecutionPointer.Id && s.Status == EnumAuditStatus.UnAudited);
                if (count == 0)
                {
                    List<Guid> ht = new();
                    //添加审批人
                    foreach (var item in userLists)
                    {
                        if (!ht.Contains(item.Id))
                        {
                            ht.Add(item.Id);
                            var key = Guid.NewGuid().ToString();
                            var result = await _abpPersistenceProvider.InsertAuditor(new PersistedWorkflowAuditor(key)
                            {
                                WorkflowId = workflow.Id,
                                ExecutionPointerId = context.ExecutionPointer.Id,
                                Status = EnumAuditStatus.UnAudited,
                                UserId = item.Id,
                                TenantId = workflow.TenantId,
                                UserIdentityName = item.Name,
                                CreationTime = DateTime.Now,
                                Remark = string.Empty,
                                CreatorId = item.Id
                            });
                        }
                    }
                }
                await _unitOfWork.SaveChangesAsync();
                DateTime effectiveDate = DateTime.MinValue;
                return ExecutionResult.WaitForEvent(ActionName, Guid.NewGuid().ToString(), effectiveDate);
            }

            //var auditCounter = await _auditorRepository.CountAsync(u => u.ExecutionPointerId == context.ExecutionPointer.Id && u.Status == EnumAuditStatus.Pass);
            //var auditCounter = await _abpPersistenceProvider.AuditorCountAsync(context.ExecutionPointer.Id, EnumAuditStatus.Pass);
            //var auditCounter = _auditorRepository.Count(u => u.ExecutionPointerId == context.ExecutionPointer.Id && u.Status == EnumAuditStatus.Pass);
            ////需全部审核通过
            //if (auditCounter < userLists.Count)
            //{
            //    context.Workflow.Status = WorkflowStatus.Complete;
            //    return ExecutionResult.Next();
            //}

            return ExecutionResult.Next();
        }
    }
}
